<template>
  <a-modal @cancel="resetModalData" :footer="null" v-model:visible="editVisible" title="修改部门">
    <a-form
        :model="formState"
        name="basic"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
    >
      <a-form-item
          label="部门名称"
          name="title"
          :rules="titleRule"
      >
        <a-input v-model:value="formState.title"/>
      </a-form-item>
      <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
        <a-space :size="20">
          <a-button type="normal" @click="handleCloseEditModal">关闭</a-button>
          <a-button type="primary" html-type="submit">修改</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import {computed, inject, onMounted, reactive, Ref, ref, watch} from "vue";

import {titleRule} from './config'
import {FormState} from "@/views/Home/EditForm/types";
import useDepartStore from "@/store/departModule";
import {message} from "ant-design-vue";

const departStore = useDepartStore()
const editVisible: Ref<boolean> = inject("editVisible") as Ref<boolean>

/* 处理表单回显 */
const currentItem = inject<any>("currentItem")
const formState = reactive<FormState>({
  title: "",
});
watch(editVisible, val => {
  if (val) {
    formState.title = currentItem.value.title
  }
})

/* 表单提交和关闭弹窗 */
const handleCloseEditModal = inject("handleCloseEditModal") as Function
const onFinish = async (values: any) => {
  const flag = await departStore.updateDepartAction({
    id: currentItem.value.ID,
    title: values.title
  })
  flag && resetModalData()
};

const onFinishFailed = (errorInfo: any) => {
  message.error(errorInfo.errorFields[0].errors[0])
};

const resetModalData = () => {
  formState.title = ""
  handleCloseEditModal()
}
</script>

<style lang="less" scoped></style>
